package middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"onvif_server/pkg/jwt"
	"os"
	"strings"
)

func Auth(j *jwt.JWT, log *zap.Logger) gin.HandlerFunc {
	noauth := false
	_noauth, ok := os.LookupEnv("NOAUTH")
	if ok && (strings.ToLower(_noauth) == "true" || _noauth == "1") {
		noauth = true
	}
	if noauth {
		return func(ctx *gin.Context) {
			ctx.Next()
		}
	}
	return func(ctx *gin.Context) {
		if ctx.ClientIP() != "127.0.0.1" {
			tokenStr := ctx.Request.Header.Get("Authorization")
			if len(tokenStr) > 0 && tokenStr[0:7] == "Bearer " {
				tokenStr = tokenStr[7:]
			}
			//头里面没有获取到，可能是ws
			if tokenStr == "" {
				//websocket
				tokenStr = ctx.Request.Header.Get("Sec-WebSocket-Protocol")
			}
			if tokenStr == "" {
				log.Error("Authorization token is empty", zap.String("url", ctx.Request.URL.String()))
				ctx.AbortWithError(401, errors.New("authorization token error"))
				return
			}
			tp, err := j.ValidateToken(tokenStr)
			if err != nil {
				log.Error("Authorization token error", zap.String("url", ctx.Request.URL.String()), zap.String("token", tokenStr), zap.Error(err))
				ctx.AbortWithError(401, err)
				return
			}
			ctx.Set("claims", tp)
		}
		ctx.Next()
	}
}
